package cn.jingzhuan.fm.ui.adapter

import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.view.View
import android.view.ViewGroup


abstract class BasePagerAdapter<T>(var list: MutableList<T>): PagerAdapter(){

    private var _count = list.size
    private var _isEndLess = false

    // 是否可以无限滚动
    var isEndLess: Boolean
        get() = _isEndLess
        set(value) {
            _isEndLess = value
            _count = if (_isEndLess) {
                Int.MAX_VALUE
            } else {
                list.size
            }
        }


    abstract  fun onBind(data: T):View

    private var _views : MutableList<out View> = list.map {
        onBind(it)
    }.toMutableList()

    override fun getCount(): Int = _count

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        try {
            (container as ViewPager?)?.addView(_views[position % _views.size], 0)
        } catch (e: Exception) {
        }
        return _views[position % _views.size]
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        super.destroyItem(container, position, `object`)
    }

    override fun isViewFromObject(view: View, obj: Any): Boolean = view == obj
}
